﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace CommonApp
{
    public static class HtmlHelpers
    {
        public static MvcHtmlString If(this MvcHtmlString result, bool condition)
        {
            if (condition)
            {
                return result;
            }
            else
            {
                return new MvcHtmlString(string.Empty);
            }
        }

        public static IEnumerable<SelectListItem> EnumToSelectList<T>(bool addEmpty = false) where T : struct
        {
            var t = typeof(T);
            if (!t.IsEnum) return null;

            var result = new List<SelectListItem>();
            if(addEmpty)
                result.Add(new SelectListItem { Value = null });

            foreach (var item in Enum.GetValues(t))
            {
                var fi = t.GetField(item.ToString());
                var attribute = fi.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault();
                var title = attribute == null ? item.ToString() : ((DescriptionAttribute)attribute).Description;
                var listItem = new SelectListItem
                {
                    Value = ((int)item).ToString(),
                    Text = title
                };
                result.Add(listItem);
            }
            return result;
        }
    }
}
